Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Python Variables

Naming variable

Python has specific guidelines for naming variables to ensure clarity and avoid errors. These rules dictate what characters you can use and where you can position them within a variable name.

Start with a Letter or Underscore

⮞ The first character of your variable name must be a letter (a-z or A-Z) or an underscore (_). ⮞ This prevents confusion with numbers, which can't be the first character.
variable name examples #Valid name _temporary_value userAge (mixing uppercase and lowercase is allowed) #Invalid 1variable (starts with a number) $price (uses a special character other than underscore)

Alphanumeric Characters and Underscores Only

Once you start with a valid character, the remaining name can consist of letters (a-z or A-Z), numbers (0-9), and underscores. This keeps variable names clear and concise.
valid and invalid variable names in python #Valid total_cost user_input2 x1 (short variable names are acceptable for temporary values) #Invalid my-name (cannot use hyphens) total@ (cannot use special characters other than underscore)

Case Sensitivity

Python treats variable names as case-sensitive. This means age, Age, and AGE are considered three different variables. Be consistent with your casing to avoid unintended behavior. Example:
Variable case sensitivity example to understand in python age = 25 Age = 30 print(age) print(Age)

Output

25 30

Reserved Words are Off-Limits

Python has a set of keywords reserved for specific language functions (like if, else, for, etc.). These keywords cannot be used as variable names. You can find a list of reserved keywords here.

Choosing Meaningful Names

While these rules ensure technical correctness, it's also crucial to choose descriptive variable names. Here are some tips: ⮞ Clarity is Key: Use names that reflect the variable's purpose. For example, customerName is clearer than x. ⮞ Descriptive Names: The longer the variable is used, the more important a clear name becomes. ⮞ Consistency: Maintain a consistent naming style throughout your code (e.g., snake_case for total_items).

Common Naming Conventions

Snake Case: Separate words with underscores (e.g., total_monthly_sales). This is the most popular convention in Python. ⮞ Camel Case: Capitalize the first letter of each word (e.g., totalPrice). This convention is less common in Python.

  📌TAGS

★python ★ variables

Tutorials